import sys

try:
    # Python 2
    import urllib
    import urllib2
    import httplib
except ImportError:
    # Python 3
    import urllib.request as urllib_request
    import urllib.parse as urllib_parse
    import http.client as httplib
def send_post_request(url, data):
    # 编码参数
    if isinstance(data, dict):
        data = urllib_parse.urlencode(data).encode('utf-8')  # Python 3 需要编码成 bytes
    elif isinstance(data, str):
        data = data.encode('utf-8')  # Python 3 中要保证数据为 bytes 类型

    # 发送 POST 请求
    if 'urllib2' in globals():  # Python 2
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        content = response.read()
        print(f"Status: {response.getcode()}")
        print(f"Response: {content}")
    else:  # Python 3
        req = urllib_request.Request(url, data)
        response = urllib_request.urlopen(req)
        content = response.read().decode('utf-8')
        print(f"Status: {response.status}")
        print(f"Response: {content}")

# 示例：向服务器发送消息
url = "http://192.168.56.1:8080"
message = "这是一个测试消息"
send_message_to_server(url, message)

if __name__ == '__main__':
    send_message_to_server(url, message)
